<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Http\Traits\UserPrivilege;
use Illuminate\Http\Request;
use Carbon\Carbon;

class Controller extends BaseController {

    use AuthorizesRequests,
        DispatchesJobs,
        ValidatesRequests,
        UserPrivilege;

    /**
     * 
     * @param type $param
     */
    protected function apiResponse($msg = '', $data = [], $status = 200, $headers = []) {
        if ($msg) {
            $data['message'] = $msg;
        }
        return response()->json($data, $status, $headers);
    }

    /**
     * 错误返回 
     * @param type $msg
     * @param type $status
     * @return type
     */
    protected function error1($msg, $status = 422) {
        $data = [];
        return $this->apiResponse($msg, $data, $status);
    }

    //错误触发
    protected function error($msg, $status = 422) {
        throw new \App\Exceptions\OperateException($msg, $status);
    }

    /**
     * 成功返回
     * @param type $msg
     * @param type $data
     * @param type $status
     * @return type
     */
    protected function success($msg = '', $data = [], $status = 200) {
        $data['status'] = 1;
        return $this->apiResponse($msg, $data, $status);
    }

    //返回验证实例
    public function validate2(Request $request, array $rules, array $messages = [], array $customAttributes = []) {
        $validator = $this->getValidationFactory()->make($request->all(), $rules, $messages, $customAttributes);

        return $validator;
    }

    //添加变化表
    protected function addAction($table = ['t_prideviceinfo']) {

        $save = [
            'updatetime' => date('Y-m-d H:i:s')
        ];
        \App\Models\Changetable::whereIn('table', $table)->update($save);
    }

    //结构化实时数据
    protected function formatRealData($data, $dptId, $prefix = 'rd_') {
        $controls = config('device.control');
        if (array_key_exists($dptId, $controls)) {
            return [];
        }
        $field = config('device.itemField');
        $surfix = config('device.surfix')[$dptId];
        $consta = config('device.consta')[$dptId];
        $desc = config('device.desc')[$dptId];
        $unit = config('device.units')[$dptId];

        $result = [];

        $item = $data->first();

        if (!$item) {
            return $result;
        }

        $num = 10;

        $result['rd_updatetime'] = $item->rd_updatetime;
        $result['rd_NetCom'] = $item->rd_NetCom;
        $result['pdi_index'] = $item->pdi_index;
        $result['num'] = $num;

        $name = $desc['name'];

        $params = [];

        // $reals = [];

        for ($i = 1; $i <= $num; $i++) {
            $itemName = "{$name}{$i}";
            foreach ($surfix as $k => $v) {
                $keyPrefix = $prefix . $k . $i;
                foreach ($field as $wKey => $warnDesc) {
                    $warnKey = $keyPrefix . $wKey;
                    $warnName = $v . $warnDesc;
                    $warnStatus = $item->$warnKey;
                    $params[] = ["name" => $itemName, "warn" => $warnName, "status" => $warnStatus];
                }
            }
            list($constaField, $constaName) = $consta;
            $constaKey = $prefix . $constaField . $i . 'consta';
            $params[] = ["name" => $itemName, "warn" => $constaName, "status" => $item->{$constaKey}];
            // $reals[]=$real;
        }
        foreach ($surfix as $k => $v) {
            $fields[] = $k;
        }
        $result['fields'] = $fields;
        $result['name'] = $name;
        $result['items'] = $params;
        $result['unit'] = $unit;
        $result['fieldDesc'] = $surfix;

        $result['icons'] = config('device.icons');
        return $result;
    }

    protected function formatArrTime($time) {
        if (!$time) {
            return [];
        }
        $result = [];
        $func = ['startOfDay', 'endOfDay'];
        foreach ($time as $k => $val) {//$zhStart->startOfDay()->toDateTimeString(), $zhEnd->endOfDay()->toDateTimeString()
            if($val) {
                $parseTime = Carbon::parse($val);
            }else{
                $parseTime = Carbon::now();
            }
            $result[] = $parseTime->{$func[$k]}()->toDateTimeString();
        }
        return $result;
    }
	
	//去除空数组
	protected function removeEmptyChildren(&$data){
		if(!$data) {
			return [];
		}

		foreach($data as $k=>&$v) {
			if(!$v['children']){
				unset($v['children']);
			}else{
				$this->removeEmptyChildren($data[$k]['children']);
			}
		}
	}

}
